<script setup>
import {inject, onMounted, ref} from "vue";
import {doDelete, doGet} from "../http/httpRequest.js";
import {confirmMessage, showMessage} from "../util/utils.js";
import {useRoute, useRouter} from "vue-router";

//定义router对象
let router = useRouter(); //调对象的方法
let route = useRoute(); //点对象的属性

//定义activityQuery对象，初始值是空
let activityQuery = ref({});
//定义验证规则
let activityRules = ref({});

//定义负责人的下拉列表数组对象
let ownerOptions = ref([{}]);

//子页面注入父页面提供的reload函数
let flushPage = inject('flush');

//加载负责人的函数
const loadOwner = () => {
  doGet('/api/user/owner', {}).then(resp => {
    if (resp.data.code === 200) {
      ownerOptions.value = resp.data.data;
    }
  })
}

//搜索函数
const onSearch = () => {
  loadActivityByPage(1);
}

//重置
const onReset = () => {
  //把所有的搜索输入框都清空
  activityQuery.value = {};
}

//定义市场活动的数组对象，初始值是空
let activityList = ref([{
  ownerDO : {}
}])
//分页时总共有多少条数据
let total = ref(0)
//分页时每页显示多少条数据
let pageSize = ref(0)

//定义市场活动id的数组，这里定义的不是响应式的数组，因为该数组不需要在html页面上进行响应式显示
let activityIdArr = [];

//勾选或取消checkbox时会执行该函数
const handleSelectionChange = (newSelection) => {
  activityIdArr = [];
  newSelection.forEach(item => {
    let id = item.id;
    activityIdArr.push(id);
  })
}

//录入市场活动
const add = () => {
  router.push('/dashboard/activity/add');
}

//批量删除市场活动
const batchDel = () => {
  //判断用户有没有选择数据，没有选数据，提示他选择要删除的数据
  if (activityIdArr.length <= 0) {
    showMessage('请选择要删除的数据', 'warning');
    return;
  }
  confirmMessage('您确定要删除这些数据吗？').then(() => { //点确定就触发then函数
    //发送请求，批量删除
    let ids = activityIdArr.join(','); // 数组[1,3,5,6,8,12]  ==> ids = "1,3,5,6,8,12";
    doDelete('/api/activity', {
      ids : ids
    }).then(resp => {
      if (resp.data.code === 200) {
        showMessage('批量删除成功', 'success');
        //局部刷新
        flushPage();
      } else {
        showMessage('批量删除失败，原因：' + resp.data.msg, 'error');
      }
    })
  }).catch(() => { //点取消就触发catch函数
    showMessage('取消批量删除', 'warning')
  })
}

//查看详情
const view = (id) => {
  router.push('/dashboard/activity/' + id);
}

const edit = (id) => {
  router.push('/dashboard/activity/edit/' + id);
}

//根据id删除市场活动
const del = (id) => {
  //删除前，让用户确认一下
  confirmMessage('您确定要删除此数据吗？').then(() => { //点确定就触发then函数
    doDelete('/api/activity/' + id, {}).then(resp => {
      if (resp.data.code === 200) {
        showMessage('删除成功', 'success')
        //页面要刷新一下，用传统方式把页面刷新一下
        //window.location.reload();
        //局部刷新
        flushPage();
      } else {
        showMessage('删除失败，原因：' + resp.data.msg, 'error')
      }
    })
  }).catch(() => { //点取消就触发catch函数
    showMessage('取消删除', 'warning')
  })
}

onMounted(() => {
  //分页查询市场活动列表数据
  loadActivityByPage(1);
})

//分页查询市场活动列表数据
const loadActivityByPage = (current) => {
  //活动开始时间
  let start = '';
  //活动结束时间
  let end = '';
  let activityTimeArr = activityQuery.value.activityTime;
  console.log(activityTimeArr);
  for (let key in activityTimeArr) {
    if (key === '0') {
      start = activityTimeArr[key];
    }
    if (key === '1') {
      end = activityTimeArr[key];
    }
  }
  doGet('/api/activitys', {
    current : current, //前面的current是参数名，后面的current是参数值
    //如果是搜索，要传6个参数给后端
    ownerId : activityQuery.value.ownerId,
    name : activityQuery.value.name,
    startTime : start,
    endTime : end,
    cost : activityQuery.value.cost,
    createTime : activityQuery.value.createTime
  }).then(resp => {
    if (resp.data.code === 200) {
      activityList.value = resp.data.data.list;
      total.value = resp.data.data.total;
      pageSize.value = resp.data.data.pageSize;
    } else {
      showMessage('数据加载失败', 'error');
    }
  })
}

//分页函数
const toPage = (value) => {
  loadActivityByPage(value);
}
</script>

<template>
  <el-form ref="searchFormRef" :inline="true" :model="activityQuery" :rules="activityRules">
    <el-form-item label="负责人" prop="ownerId">
      <el-select
          v-model="activityQuery.ownerId"
          placeholder="请选择负责人"
          style="width: 215px;"
          clearable
          @click="loadOwner">
        <el-option
            v-for="item in ownerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="活动名称" prop="name">
      <el-input v-model="activityQuery.name" placeholder="请输入活动名称" clearable />
    </el-form-item>

    <el-form-item label="活动时间" prop="activityTime">
      <el-date-picker
          v-model="activityQuery.activityTime"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"/>
    </el-form-item>

    <el-form-item label="活动预算" prop="cost">
      <el-input v-model="activityQuery.cost" placeholder="请输入活动预算" clearable />
    </el-form-item>

    <el-form-item label="创建时间" prop="createTime">
      <el-date-picker
          v-model="activityQuery.createTime"
          type="datetime"
          placeholder="请选择创建时间"
          value-format="YYYY-MM-DD HH:mm:ss"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSearch">搜 索</el-button>
      <el-button type="primary" plain @click="onReset">重 置</el-button>
    </el-form-item>
  </el-form>
  <br/>
  <el-button type="primary" @click="add">录入市场活动</el-button>
  <el-button type="danger" @click="batchDel">批量删除</el-button>

  <el-table
      :data="activityList"
      style="width: 100%"
      @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55"/>
    <el-table-column type="index" label="序号" width="60"/>
    <el-table-column prop="ownerDO.name" label="负责人"/>
    <el-table-column property="name" label="活动名称"/>
    <el-table-column property="startTime" label="开始时间"/>
    <el-table-column property="endTime" label="结束时间"/>
    <el-table-column property="cost" label="活动预算"/>
    <el-table-column property="createTime" label="创建时间"/>
    <el-table-column label="操作" width="230">
      <template #default="scope">
        <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination :background="true"
                 layout="prev, pager, next, jumper, ->, total"
                 :total="total"
                 :page-size="pageSize"
                 @current-change="toPage"/>
</template>

<style scoped>
.el-table {
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>